package cn.itcast.nio.c2;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

@Slf4j
public class WriteServer2 {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));
        while(true){
            selector.select();
            Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
            while(iter.hasNext()){
                SelectionKey key = iter.next();
                iter.remove();
                if(key.isAcceptable()){
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    SelectionKey sckey = sc.register(selector, 0, null);
                    //如果这里给加了关注事件 那么后面
                    sckey.interestOps(SelectionKey.OP_READ);
                    //1.向客户端发送大量数据
                    StringBuilder sb = new StringBuilder();
                    for(int i = 0;i<300000000;i++){
                        sb.append("a");
                    }
                    ByteBuffer buffer = StandardCharsets.UTF_8.encode(sb.toString());
                    //2.返回实际写入的字节数
                    int write = sc.write(buffer);
                    log.debug("write...{}",write);
                    //3.判断是否还有剩余内容
                    if (buffer.hasRemaining()){
                        //4.关注可写事件 不覆盖他原本的事件
                        sckey.interestOps(sckey.interestOps() + SelectionKey.OP_WRITE);
                        //未写完的buffer 作为附件
                        sckey.attach(buffer);
                    }
                }else if(key.isWritable()){
                    SocketChannel sc = (SocketChannel) key.channel();
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    int write = sc.write(buffer);
                    log.debug("write...{}",write);
                    //清理
                    if(!buffer.hasRemaining()){
                        key.attach(null);
                        key.interestOps(key.interestOps() - SelectionKey.OP_WRITE);
                    }

                }
            }
        }
    }
}
